<template>
  <div>
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form class="demo-table-expand" inline label-position="left">
            <el-form-item>
              <div v-if="props.row.attr_vals!==''">
                <el-tag
                  v-for="(tag,index) in props.row.attr_vals.split(' ')"
                  :key="index"
                  :disable-transitions="false"
                  closable
                  @close="handleClose(props.row,index,props.$index)">
                  {{ tag }}
                </el-tag>
              </div>
              <!--            一次只能显示一个input-->
              <el-input
                v-if="inputVisible&&props.row.attr_id===isIndex"
                ref="saveTagInput"
                v-model.trim="inputValue"
                class="input-new-tag"
                size="small"
                @blur="showInput('')"
                @keyup.enter.native="handleInputConfirm(props.row,props.$index)"
              >
                <!--              获取当前行用于渲染的数组字符串-->
              </el-input>
              <el-button
                v-else class="button-new-tag"
                size="small"
                @click="showInput(props.row.attr_id)"
              >+ New Tag
              </el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        label="#"
        prop="id"
        type="index">
      </el-table-column>
      <el-table-column
        label="参数名称"
        prop="attr_name">
      </el-table-column>
      <el-table-column
        label="操作">
        <template v-if="isShow" slot-scope="scope">
          <el-button icon="el-icon-edit"
                     size="mini"
                     type="primary"
                     @click="setMany(scope.$index, scope.row)"
          >修改
          </el-button>
          <el-button icon="el-icon-delete"
                     size="mini"
                     type="danger"
                     @click="removeMany(scope.$index,scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--      编辑动态参数-->
    <el-dialog :visible.sync="putParamsVisible" title="编辑动态参数">
      <el-form ref="putParams" :model="attr_name" :rules="rules">
        <el-form-item label="动态参数:" label-width="100px" prop="name">
          <el-input v-model.trim="attr_name.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="putParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="putParams">确 定</el-button>
      </div>
    </el-dialog>
    <!--      /编辑动态参数-->
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
import { deleteParams, poshCategoriesMany, poshCategoriesOnly } from '@/api/commodity'

const {
  mapMutations,
  mapState
} = createNamespacedHelpers('params')
export default {
  name: 'ParamsTable',
  data () {
    return {
      inputVisible: false,
      inputValue: '',
      isIndex: '',
      putParamsVisible: false,
      rules: {
        name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      },
      paramsFrom: {},
      attr_name: {
        name: ''
      },
      index: ''
    }
  },
  methods: {
    ...mapMutations(['putListItem', 'putListItemName', 'deleteParamsList']),
    setMany (index, item) {
      // console.log(index, item)
      this.index = index
      this.paramsFrom = item
      this.attr_name.name = this.paramsFrom.attr_name
      // console.log(this.paramsFrom)
      this.putParamsVisible = true
    },
    // 确定提交
    async putParams () {
      await this.$refs.putParams.validate((valid) => {
        if (valid) {
          // console.log(1)
          this.paramsFrom.attr_name = this.attr_name.name
          this.putName(this.paramsFrom, this.paramsFrom.attr_vals, this.index)
        }
      })
    },
    // 删除参数
    removeMany (index, item) {
      this.index = index
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(item.attr_id, this.id)
        deleteParams(item.attr_id, this.id).then(res => {
          if (res.meta.status === 200) {
            // 与本地同步
            this.deleteParamsList([this.isShow, this.index])
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
          } else {
            this.$message.error(res.meta.msg)
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除小标签
    handleClose (obj, i, index) {
      console.log(obj, i, index)
      const arr = obj.attr_vals.split(' ')
      arr.splice(i, 1)
      // console.log(arr)
      // 调用方法修改小标签
      const arrSre = arr.join(' ')
      this.put(obj, arrSre, index)
    },
    // 添加小标签
    handleInputConfirm (obj, index) {
      if (this.inputValue === '') return
      const arr = obj.attr_vals.split(' ')
      arr.push(this.inputValue)
      // console.log(arr.join(','))
      // console.log(obj.attr_id, obj.attr_name, arr.join(' '), this.id)
      // 如果第一项为空就删除他 bug
      if (arr[0] === '') arr.splice(0, 1)
      // 调用方法修改小标签
      // console.log(arr, arr.join(' '))
      const arrSre = arr.join(' ')
      this.put(obj, arrSre, index)
    },
    // 单独修改小标签
    async put (obj, arr, index) {
      try {
        if (this.isShow) {
          await poshCategoriesMany(obj.attr_id, obj.attr_name, arr, this.id)
        } else {
          await poshCategoriesOnly(obj.attr_id, obj.attr_name, arr, this.id)
        }
        // 修改仓库数据
        this.putListItem([this.isShow, index, arr])
        // 清空输入框
        this.paramsFrom = ''
        this.inputVisible = false
      } catch (e) {
        this.$message({
          type: 'error',
          message: '修改失败'
        })
      }
    },
    // 单独修改名字
    async putName (obj, arr, index) {
      console.log(obj.attr_id, obj.attr_name, arr, this.id)
      try {
        if (this.isShow) {
          await poshCategoriesMany(obj.attr_id, obj.attr_name, arr, this.id)
        } else {
          await poshCategoriesOnly(obj.attr_id, obj.attr_name, arr, this.id)
        }
        // 修改仓库数据
        this.putListItemName([this.isShow, index, obj.attr_name])
        // 清空输入框
        this.putParamsVisible = false
      } catch (e) {
        this.$message({
          type: 'error',
          message: '修改失败'
        })
      }
    },
    // 显示添加标签的输入框
    showInput (index) {
      this.inputVisible = !this.inputVisible
      this.isIndex = index
      setTimeout(() => {
        // 获取焦点
        // eslint-disable-next-line no-unused-expressions
        this.$refs.saveTagInput?.$el?.__vue__.$refs.input.focus()
      }, 0)
    }
  },
  computed: {
    ...mapState(['id'])
  },
  props: {
    tableData: {
      type: Array
    },
    isShow: {
      type: Boolean
    }
  }
}
</script>

<style scoped>

</style>
